package com.booktrade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.booktrade.entity.Notifications;
import com.booktrade.mapper.NotificationsMapper;
import com.booktrade.service.INotificationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 消息通知表，存储系统发送给用户的通知信息 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class NotificationsServiceImpl extends ServiceImpl<NotificationsMapper, Notifications> implements INotificationsService {
    private final NotificationsMapper notificationMapper;

    @Override
    public List<Notifications> getNoReadmessage(Integer userId) {
        LambdaQueryWrapper<Notifications> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notifications::getUserId, userId)
                .eq(Notifications::getIsRead, false)
                .orderByDesc(Notifications::getCreatedAt);
        return notificationMapper.selectList(queryWrapper);
    }

    /**
     * 创建通知
     */
    public void createNotification(Integer userId, String message) {
        Notifications notification = new Notifications();
        notification.setUserId(userId);
        notification.setMessage(message);
        notification.setIsRead(false);
        notificationMapper.insert(notification);
    }

    /**
     * 根据用户ID获取未读通知
     */
    public List<Notifications> getNotificationsByUserId(Integer userId) {
        LambdaQueryWrapper<Notifications> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notifications::getUserId, userId)
                .orderByDesc(Notifications::getCreatedAt);
        return notificationMapper.selectList(queryWrapper);
    }

    /**
     * 标记通知为已读
     */
    public void markAsRead(Integer notificationId) {
        Notifications notification = notificationMapper.selectById(notificationId);
        if (notification != null && !notification.getIsRead()) {
            notification.setIsRead(true);
            notificationMapper.updateById(notification);
        }
    }
}
